var userRequestUrl = '/dashu-authority/user';
var comeRequestUrl = '/dashu-authority/application';
var menuRequestUrl = '/dashu-authority/menu';
var buttonOperateUrl = '/dashu-authority/buttonOperate';
var authorRequestUrl = "/dashu-authority/competence";
var parStr = "";
//获原始树结构所选节点的数据数组
function getTreeSelected()
{
    var nodes = $('#tt').tree('getChecked');
    var arr = new Array();
    for (var i = 0; i < nodes.length;i++) {
        arr.push(nodes[i]);
        myFuc(nodes[i]);
    }
    return arr;


    //内部递归函数
    function myFuc(n) {
        var parent = $('#tt').tree('getParent', n.target);
        if (parent == null) return;
        if (isExistItem(parent)) return;
        arr.push(parent);
        myFuc(parent);
    }
    //验证节点是否已存在数组中
    function isExistItem(item)
    {
        var flag = false;
        for (var i = 0; i < arr.length;i++)
        {
            if (arr[i] == item) {
                flag = true; break;
            }
        }
        return flag;
    }

}


function isChecked(rowData){  
    var rows = $("#authDataGrid").datagrid('getSelections');  
    for(var i=0;i<rows.length;i++){  
        if(rowData.id==rows[i].id){  
        return true;  
        }  
    }  
    return false;  
} 

function arrValueIndex(arrValue,val) {  
    for (var i = 0; i < arrValue.length; i++) {  
        if (arrValue[i].soreNum == val) return i;  
    }  
    return -1;  
}; 
 

function tree(applicationId,personnelId){
	$("#user_district").show();
	// 初始化tree					
		$('#tt').tree({
			url : '',
			checkbox:true,
			animate:true,
			cascadeCheck:false,
			onCheck: function (node, checked) {
			},
		        onClick:function (node, data) {
		        	initAuthDataGrid(node.id);
		        },
		        onLoadSuccess: function (node, data) {//数据加载完成事件
		        	
	            },
			onBeforeExpand : function(node, param) {
				// 加载子节点 为了避免重复加载 ，用load_flag变量来控制，0为未加载，1为已加载
				if (node.load_flag == 0) {
					var str = "path_code=" + node.id + "&type="
							+ node.child_type;
					var att_url = authorRequestUrl+'/getMenuTreeAuthorityAssign?DASHU_AUTH_TOKEN='+token+"&applicationId="+applicationId+"&personnelId="+personnelId+"&personnelType=personnelRole"
							+ str;
					// 节点加载
					setTreeJson("#tt", att_url, node);
				}
			}
		});
		var att_url = authorRequestUrl+'/getMenuTreeAuthorityAssign?DASHU_AUTH_TOKEN='+token+"&applicationId="+applicationId+"&personnelId="+personnelId+"&personnelType=personnelRole";
		setTreeJson("#tt", att_url, null);
}



function initAuthDataGrid(menuId) {
	var str ="";
	var uStr="";
	$("#authDataGrid").datagrid({
		loadMsg:"数据加载中，请稍后……",
		url : buttonOperateUrl+'/findAllByPagingAndAuth.json?DASHU_AUTH_TOKEN='+token+'&menuId='+menuId,
		//url : baseDeviceInfoRequestUrl+'/findAllDeviceUser.json?pathCode='+pathCode,
		toolbar : [{
			text : '添加',
			iconCls : 'icon-add',
			handler : function() {
				formsubmitUrl = buttonOperateUrl+'/saveDeviceUser.json?DASHU_AUTH_TOKEN='+token;
				clearFrom(dataFormDiv);
				setDialog("#dlgDIV", '','新增');
			}
		},'-',{
			text : '删除',
			iconCls : 'icon-cancel',
			handler : function() {
				var rows = $("#authDataGrid").datagrid("getSelections");
				if (rows.length == 0 ) {
					$.messager.alert("操作提示", "请至少选择一行", "info");
				} else {
					var ids = [];
					for (var i = 0; i < rows.length; i++) {
						ids.push(rows[i].id);
					}
					$.messager.confirm('确认','您确认想要删除选中的权限数据？',function(r) {
						if (r) {
							$.ajax({
								type : "POST",
								dataType : 'html',
								url : baseDeviceInfoRequestUrl+'/deleteDeviceUserByIds.json?pathCode='+pathCode+'&ids='+ids,
								success : function(data) {
									var obj = eval('('+ data+ ')');
									console.log(JSON.stringify(obj));
									if (obj.status == 1) {
										$.fn.messageInfoTip(data);
										$("#authDataGrid").datagrid('reload');
									}
								},
								error: function(textStatus){
									if(console){
										console.error("ajax出现异常："+textStatus);
									}
									alert(textStatus);
								}
							});
						}else{
							return false;
						}
					});
				}
		}} ],
		width : '100%',
		pagination : true,
		pageSize : 10,
		singleSelect : false,
		striped : true,
		sortOrder : 'asc',
		rownumbers : true,
		onLoadSuccess : function(data) {
			$("#authDataGrid").datagrid('clearSelections');
			var nodes = $('#tt').tree('getSelected');
			if(nodes!=null){
				 var rowData = data.rows; 
				 var c= auths[menuId];
				 console.log(c);
				 if(rowData!=null && rowData.length>0){
				    $.each(rowData,function(index,row){//遍历JSON 
				    	if(auths!=null && Object.getOwnPropertyNames(auths).length>0){
				    		if(typeof(c) != undefined && c!=null){
				    			if(checkProduct(Number(c),Number(row.soreNum))){
					    			$("#authDataGrid").datagrid("selectRow", index);  
					    		}
				    		}
						}  
				    });  
				 }
			}
			// auths这个参数在apiCommon.js文件中
			
			if(auths!=null){
				 var rowData = data.rows; 
				var menuAuth = auths[menuId];
				 if(rowData!=null && rowData.length>0){
					 $.each(rowData,function(index,row){//遍历JSON 
						 if(checkProduct(Number(menuAuth),Number(row.soreNum))){
								$("#authDataGrid").datagrid("selectRow", index);  
							}; 
					 });
				 }
			}
		},
		onCheck:function(rowIndex,rowData){
		},
		loadFilter:function(data){
			return parseDataGrid(data);
		},
		onLoadError : function() {
		},

		onClickRow:function(rowIndex,rowData){
			var checks = $("#authDataGrid").datagrid('getChecked');
			var nodes = $('#tt').tree('getSelected');
			
			//获取父级
			var nodePar = $('#tt').tree('getParent', nodes.target);
			
			if(checks!=null && checks.length>0){				
				for (var i = 0; i < checks.length; i++) {
					if(rowData.menuId==null||nodes.id==checks[i].menuId){					
						var nodesss = $('#tt').tree('find', nodes.id); 						
						$('#tt').tree('check',nodesss.target); 
						if (nodePar != null) {              
							$("#tt").tree('check', nodePar.target);
						}
					}				
				}
			}else{
				if(rowData.menuId==null||nodes.id==rowData.menuId){
					var nodesss = $('#tt').tree('find', nodes.id); 
		        	if(nodesss.checked==false){
		        		 $('#tt').tree('check',nodesss.target); 
		        	}else{
		        		 $('#tt').tree('uncheck',nodesss.target); 
		        	}if (nodePar != null) {
		        		if(nodePar.checked==false){
			        		 $('#tt').tree('check',nodePar.target); 
			        	}else{
			        		 $('#tt').tree('uncheck',nodePar.target); 
			        	}
					}	
				}
				 str="";
				 parStr = "";
				 delete auths[nodePar.id];
				 delete auths[nodes.id]; 
				
			}
			
			
			if(isChecked(rowData)){	 //选中
				var checks  = $("#authDataGrid").datagrid('getChecked');
				console.log(checks);
				str = "";
				for (var i = 0; i < checks.length; i++) {	
				  if(str!=null && ""!=str){
					  str += ","+checks[i].soreNum;
					}else{
						str += checks[i].soreNum;
					}
				}
				  
				  //父级加权重值
				  if(nodePar!=null){
				  if("2"==rowData.soreNum){
					  if(parStr!=null && ""!=parStr){
							parStr += ","+rowData.soreNum;
						}else{
							parStr += rowData.soreNum;
						}  
				  }else if("3"==rowData.soreNum){
					  if(parStr!=null && ""!=parStr){
							parStr += ","+rowData.soreNum;
						}else{
							parStr += rowData.soreNum;
						}  
				  }else if("4"==rowData.soreNum){
					  if(parStr!=null && ""!=parStr){
							parStr += ","+rowData.soreNum;
						}else{
							parStr += rowData.soreNum;
						}  
				  }else if("5"==rowData.soreNum){
					  if(parStr!=null && ""!=parStr){
							parStr += ","+rowData.soreNum;
						}else{
							parStr += rowData.soreNum;
						}  
				  }else if("1"==rowData.soreNum){
					  if(parStr!=null && ""!=parStr){
							parStr += ","+rowData.soreNum;
						}else{
							parStr += rowData.soreNum;
						}  
				  }
				}
				  
				  
			 }else{  //没选中	
				 
				var checks  = $("#authDataGrid").datagrid('getChecked');				 
				str = "";				
				//父级加权重值
				parStr="";
				
					for (var i = 0; i < checks.length; i++) {						
						if(str!=null && ""!=str){
							str += ","+checks[i].soreNum;
						}else{
							str += checks[i].soreNum;
					}
										
						//父级加权重值
						if(nodePar!=null){
							  if("2"==checks[i].soreNum){
								  if(parStr!=null && ""!=parStr){
										parStr += ","+checks[i].soreNum;
									}else{
										parStr += checks[i].soreNum;
									}  
							  }else if("3"==checks[i].soreNum){
								  if(parStr!=null && ""!=parStr){
										parStr += ","+checks[i].soreNum;
									}else{
										parStr += checks[i].soreNum;
									}  
							  }else if("4"==checks[i].soreNum){
								  if(parStr!=null && ""!=parStr){
										parStr += ","+checks[i].soreNum;
									}else{
										parStr += checks[i].soreNum;
									}  
							  }else if("5"==checks[i].soreNum){
								  if(parStr!=null && ""!=parStr){
										parStr += ","+checks[i].soreNum;
									}else{
										parStr += checks[i].soreNum;
									}  
							  }else if("1"==checks[i].soreNum){
								  if(parStr!=null && ""!=parStr){
										parStr += ","+checks[i].soreNum;
									}else{
										parStr += checks[i].soreNum;
									}  
							  }
							}
				 }
					
			 }
			
			
			if(rowData.soreNum==1){  //为第一条数据要走一次“选中”的步骤
				if(isChecked(rowData)){
					$("#authDataGrid").datagrid("selectRow", 0); 
					var checks  = $("#authDataGrid").datagrid('getChecked');
					str = "";
					for (var i = 0; i < checks.length; i++) {	
					  if(str!=null && ""!=str){
						  str += ","+checks[i].soreNum;
						}else{
							str += checks[i].soreNum;
						}
					}
					//父级加权重值
					if(nodePar!=null){
						if(parStr!=null && ""!=parStr){
							parStr += ","+rowData.soreNum;
						}else{
							parStr += rowData.soreNum;
						}
					}
				}else{
					$("#authDataGrid").datagrid("unselectRow", 0);
					var checks  = $("#authDataGrid").datagrid('getChecked');
					str = "";
					//父级加权重值
					 parStr="";
					 
						for (var i = 0; i < checks.length; i++) {
							
							//当前节点加权重值
							if(str!=null && ""!=str){
								str += ","+checks[i].soreNum;
							}else{
								str += checks[i].soreNum;
						}
							 
							//父级加权重值
							 if(nodePar!=null){
								  if("2"==checks[i].soreNum){
									  if(parStr!=null && ""!=parStr){
											parStr += ","+checks[i].soreNum;
										}else{
											parStr += checks[i].soreNum;
										}  
								  }else if("3"==checks[i].soreNum){
									  if(parStr!=null && ""!=parStr){
											parStr += ","+checks[i].soreNum;
										}else{
											parStr += checks[i].soreNum;
										}  
								  }else if("4"==checks[i].soreNum){
									  if(parStr!=null && ""!=parStr){
											parStr += ","+checks[i].soreNum;
										}else{
											parStr += checks[i].soreNum;
										}  
								  }else if("5"==checks[i].soreNum){
									  if(parStr!=null && ""!=parStr){
											parStr += ","+checks[i].soreNum;
										}else{
											parStr += checks[i].soreNum;
										}  
								  }else if("1"==checks[i].soreNum){
									  if(parStr!=null && ""!=parStr){
											parStr += ","+checks[i].soreNum;
										}else{
											parStr += checks[i].soreNum;
										}  
								  }
							}
					 }
				}
			}else{	
				var checks  = $("#authDataGrid").datagrid('getChecked');
				if(checks!=null && checks.length>0){
					var rowsss=$('#authDataGrid').datagrid('getRows')[0]; //获取第一条数据
					if(!isChecked(rowsss)){
						$("#authDataGrid").datagrid("selectRow", 0);
						if(str!=null && ""!=str){
							str += ","+rowsss.soreNum;
						}else{
							str += rowsss.soreNum;
						}
						
						//父级加权重值
						if(nodePar!=null){
							if(parStr!=null && ""!=parStr){
								parStr += ","+rowsss.soreNum;
							}else{
								parStr += rowsss.soreNum;
							}
						}
					}
				}
				
			}
			
			
			
			if(auths!=null ){
				if(auths[menuId]!=null){
					delete auths[menuId];
				}
					auths = auths;
				
				
				//auths[parseInt(menuId)]=getProduct(aStrs);	
			}
			
			if(str!=null && ""!=str){
				var aStrs = str.split(",");
				auths[parseInt(menuId)]=getProduct(aStrs);
			}
			
			if(parStr!=null && ""!=parStr ){
				var parStrs = parStr.split(",");
				auths[parseInt(nodePar.id)]=getProduct(parStrs);
			}

			
			
			console.log(auths);
			
		},
		columns : [ [ 
		             	{
		             		field : 'ck',
		             		checkbox : true
		             	},
				       {	field : 'id',
							title : 'ID',
							width : 65,
							align : 'center',
							hidden : true,
							sortable : true
						},{
							field : 'name',
							title : '名称',
							width : 90,
							align : 'center',
							sortable : true
						},{
							field : 'menuName',
							title : '菜单名称',
							width : 90,
							align : 'center',
							sortable : true
						},{
							field : 'soreNum',
							title : '编号',
							width : 90,
							align : 'center',
							sortable : true
						}
				         ] ]
	});
}


//$.ajax({
//	type : "POST", //提交方式 
//	url : cc+'/saveMenuAuthority',
//	dataType:'json',
//	data:{"value":JSON.stringify(auths),"personnelId":$("#personnelId").val(),"personnelType":$("#personnelType").val(),"applicationId":$("#applicationId").val()},
//	success : function(result) {//返回数据根据结果进行相应的处理
//		
//	}
//}) 


